<template>
	<view class="search-container">
		<!-- 搜索框 -->
		<view class="search-bar">
			<input v-model="keyword" placeholder="请输入地点" class="search-input" @confirm="searchPlace" />
			<image src="/static/img/search.png" class="search-icon" @click="searchPlace" />
		</view>

		<!-- 搜索结果 -->
		<view v-for="item in result" :key="item.id" @click="selectPlace(item)" class="search-result" v-if="resultVisible">
			<text>{{ item.title }}</text>
		</view>
	</view>
</template>

<script>
	import {
		TENCENT_MAP_KEY
	} from '@/common/map-key.js';

	export default {
		data() {
			return {
				keyword: '',
				result: [],
				resultVisible:false,   //是否显示搜索结果
			};
		},
		methods: {
			searchPlace() {
				if (!this.keyword) {
					return
				};
				uni.request({
					url: `https://apis.map.qq.com/ws/place/v1/search`,
					data: {
						keyword: this.keyword,
						boundary: 'region(上海,0)',
						key: TENCENT_MAP_KEY
					},
					success: (res) => {
						console.log(res);
						if (res.data.status === 0) {
							this.result = res.data.data;
							this.resultVisible=true
						} else {
							console.error(res.data.message);
						}
					}
				});
			},
			selectPlace(item) {
				console.log(item);
				const lat = item.location.lat;
				const lng = item.location.lng;
				this.keyword=item.title;
				this.$emit('select-place', {
					lat,
					lng,
					title: item.title,
					destination:item
				});
				this.resultVisible=false
			}
		}
	};
</script>

<style scoped>
	.search-container {
		padding: 15px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		background-color: #f1f1f1;
		border-radius: 25px;
		padding: 5px 15px;
		box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.1);
	}

	.search-input {
		flex: 1;
		height: 40px;
		background-color: transparent;
		border: none;
		outline: none;
		font-size: 16px;
		color: #333;
	}

	.search-icon {
		width: 20px;
		height: 20px;
		margin-left: 10px;
		cursor: pointer;
	}

	.search-result {
		padding: 10px 0;
		border-bottom: 1px solid #ddd;
	}

	.search-result text {
		font-size: 14px;
		color: #666;
	}
</style>